SPORE.$Import('core.core');

/*
---

name: Object

description: Object generic methods

license: MIT-style license.

requires: Type

provides: [Object, Hash]

...
*/

SPORE.register('core.object',function($ns){

	var hasOwnProperty = Object.prototype.hasOwnProperty;
	
	Object.extend({
	
		subset: function(object, keys){
			var results = {};
			for (var i = 0, l = keys.length; i < l; i++){
				var k = keys[i];
				if (k in object) results[k] = object[k];
			}
			return results;
		},
	
		map: function(object, fn, bind){
			var results = {};
			for (var key in object){
				if (hasOwnProperty.call(object, key)) results[key] = fn.call(bind, object[key], key, object);
			}
			return results;
		},
	
		filter: function(object, fn, bind){
			var results = {};
			for (var key in object){
				var value = object[key];
				if (hasOwnProperty.call(object, key) && fn.call(bind, value, key, object)) results[key] = value;
			}
			return results;
		},
	
		every: function(object, fn, bind){
			for (var key in object){
				if (hasOwnProperty.call(object, key) && !fn.call(bind, object[key], key)) return false;
			}
			return true;
		},
	
		some: function(object, fn, bind){
			for (var key in object){
				if (hasOwnProperty.call(object, key) && fn.call(bind, object[key], key)) return true;
			}
			return false;
		},
	
		keys: function(object){
			var keys = [];
			for (var key in object){
				if (hasOwnProperty.call(object, key)) keys.push(key);
			}
			return keys;
		},
	
		values: function(object){
			var values = [];
			for (var key in object){
				if (hasOwnProperty.call(object, key)) values.push(object[key]);
			}
			return values;
		},
	
		getLength: function(object){
			return Object.keys(object).length;
		},
	
		keyOf: function(object, value){
			for (var key in object){
				if (hasOwnProperty.call(object, key) && object[key] === value) return key;
			}
			return null;
		},
	
		contains: function(object, value){
			return Object.keyOf(object, value) != null;
		},
	
		toQueryString: function(object, base){
			var queryString = [];
	
			Object.each(object, function(value, key){
				if (base) key = base + '[' + key + ']';
				var result;
				switch (typeOf(value)){
					case 'object': result = Object.toQueryString(value, key); break;
					case 'array':
						var qs = {};
						value.each(function(val, i){
							qs[i] = val;
						});
						result = Object.toQueryString(qs, key);
					break;
					default: result = key + '=' + encodeURIComponent(value);
				}
				if (value != null) queryString.push(result);
			});
	
			return queryString.join('&');
		}
	
	});

});